package com.sgb.member.ui.fragment;

import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.member.MemberConfig;
import com.sgb.member.PickCateType;
import com.sgb.member.R;
import com.sgb.member.databinding.FragmentMemberInviteOrApplyBinding;
import com.sgb.member.di.DaggerMemberFragComponent;
import com.sgb.member.di.MemberFragModule;
import com.sgb.member.entity.QualityMemberBean;
import com.sgb.member.ui.activity.ComApplyOrInvitePersonActivity;
import com.sgb.member.ui.activity.ComApplyOrInvitePersonShenPiActivity;
import com.sgb.member.ui.activity.MemberApplyJoinActivity;
import com.sgb.member.ui.activity.MemberInviteJoinActivity;
import com.sgb.member.ui.activity.MemberInviteOrApplyActivity;
import com.sgb.member.ui.activity.PersonApplyJoinActivity;
import com.sgb.member.ui.activity.PersonInviteJoinActivity;
import com.sgb.member.ui.adapter.MemberInviteAdapter;
import com.sgb.member.view_model.MemberInviteOrApplyModel;
import com.sgb.member.weight.MemberCommonDialog;
import com.sgb.member.weight.threefliter.MThreeLevelFilterWindow;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.xrecyclerview.LoadingMoreFooter;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class MemberInviteOrApplyFragment extends AppLazyFragment implements MemberStatusView.OnChooseListener {

    @Inject
    MemberInviteOrApplyModel sModel;
    private FragmentMemberInviteOrApplyBinding mBinding;
    private int mCurPage;
    private int comType; // 类型 0个人 1企业 2团队
    private String mTripStr; // 请选择需要邀请的企业
    private String mApproveType; // 邀请加盟审批类型 inviteJoinCompany 申請加盟审批类型 applyJoinCompany
    private QualityMemberBean qualityMemberBean;
    private MemberInviteAdapter mAdapter;

    private String mBusinessNo;
    private String mAreaNo;
    private String userType = "";


    public static MemberInviteOrApplyFragment newInstance(int type, int comType) {
        MemberInviteOrApplyFragment fragment = new MemberInviteOrApplyFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("INDEX_PAGE", type);
        bundle.putInt("COM_TYPE", comType);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMemberFragComponent.builder()
                .appComponent(appComponent)
                .memberFragModule(new MemberFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_member_invite_or_apply, container, false);
        mBinding.setLifecycleOwner(this);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        assert getArguments() != null;
        mCurPage = getArguments().getInt("INDEX_PAGE", 0);
        comType = getArguments().getInt("COM_TYPE", 0);
        mBinding.inviteSizeLayout.setVisibility(View.VISIBLE);
        mBinding.tvChooseMember.setText(Html.fromHtml(String.format(getResources().getString(R.string.select_apply_member), "")));
        mBinding.tvInviteJoin.setOnClickListener(this);
        switch (mCurPage) {
            case 0:
                mBinding.tvInviteJoin.setText("邀请加盟");
                mTripStr = "请选择需要邀请的企业";
                mApproveType = "inviteJoinCompany";
                break;
            case 1:
                mBinding.tvInviteJoin.setText("申请加盟");
                mTripStr = "请选择需要申请的企业";
                mApproveType = "applyJoinCompany";
                break;
        }
        initPopup();
        initRecycler();
    }

    @Override
    protected void onLazyLoad() {
        sModel.getCompanyServiceTypeCateGory(PickCateType.TYPE_0);
        loadData(false);
    }

    public void loadData(boolean isLoadMore) {
        String searchText = "";
        if (getActivity() != null) {
            searchText = ((MemberInviteOrApplyActivity) getActivity()).getSearchText();
        }
        if (!isLoadMore) {
            qualityMemberBean = null;
            mBinding.tvChooseMember.setText(Html.fromHtml(String.format(getResources().getString(R.string.select_apply_member), "")));
        }

        if (comType == MemberConfig.WEBSITE_FOR_PERSONAL) {//个人 继续用老接口
            sModel.getInviteOrApplyCompanyList(mCurPage, isLoadMore, searchText, mBusinessNo, mAreaNo);
        } else {//企业  用个人和企业混合接口
            sModel.personAndCompanyList(isLoadMore, searchText, mBusinessNo, mAreaNo, userType);
        }

    }

    @Override
    public void onMultiClick(View v) {
        if (v == mBinding.tvInviteJoin) {
            if (mCurPage == 0) {//邀请加盟
                if (!MemberConfig.getInstance().isHavePermission("14_yaoqinghuiyuan1")) {
                    MToast.showToast(getActivity(), "没有权限操作，请找企业管理员分配权限");
                    return;
                }
            } else {
                if (!MemberConfig.getInstance().isHavePermission("14_shenqingjiameng1")) {
                    MToast.showToast(getActivity(), "没有权限操作，请找企业管理员分配权限");
                    return;
                }
            }
            // 跳转邀请加盟申请页
            if (qualityMemberBean != null) {
                String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
                sModel.getProcessStatus(companyNo, mApproveType);
            } else {
                MToast.showToast(getContext(), mTripStr);
            }
        }
    }


    // 更新审批回调处理
    public void updateProcessStatus(String status) {
        // 有审批时：弹出审批确认弹窗，具体如原型所示，点击去填写跳转到邀请审批信息填写页
        // 无审批时：点击去填写跳转到邀请信息填写页
        if (status.equals("1")) {
            MemberCommonDialog dialog = new MemberCommonDialog(new MemberCommonDialog.SimpleListener() {
                @Override
                public void onPositive(Object... objects) {
                    // 跳转填写审批信息// 审批类型 1 申请加盟(固定传1就行) 2邀请加盟
                    jumpJoinPage(status);
                }
            }, MemberCommonDialog.STYLE_INVITE_JOIN);
            dialog.show(getActivity(), "MemberCommonDialog");
        } else {
            jumpJoinPage(status);
        }
    }

    private void jumpJoinPage(String status) {
        // 跳转邀请加盟申请页
        switch (mCurPage) {
            case 0: // 邀请加盟
                if (comType == MemberConfig.WEBSITE_FOR_PERSONAL) {
                    PersonInviteJoinActivity.start(getActivity(), qualityMemberBean, false);//个人 邀请 企业
                } else {
                    if (qualityMemberBean.getUserType().equals("1")) {
                        MemberInviteJoinActivity.start(getActivity(), qualityMemberBean);//企业 邀请 企业
                    } else {
                        if (status.equals("1")) {//有审批
                            ComApplyOrInvitePersonShenPiActivity.start(requireActivity(), qualityMemberBean, false, mCurPage);//  企业  邀请  个人 有审批
                        } else {
                            ComApplyOrInvitePersonActivity.start(requireActivity(), qualityMemberBean, false, mCurPage); //    企业  邀请  个人
                        }
                    }
                }
                break;
            case 1: // 申请加盟
                if (comType == MemberConfig.WEBSITE_FOR_PERSONAL) {
                    PersonApplyJoinActivity.start(getActivity(), qualityMemberBean, false);//个人 申请 企业
                } else {
                    if (qualityMemberBean.getUserType().equals("1")) {
                        MemberApplyJoinActivity.start(getActivity(), qualityMemberBean);//企业 申请 企业
                    } else {
                        if (status.equals("1")) {//有审批
                            ComApplyOrInvitePersonShenPiActivity.start(requireActivity(), qualityMemberBean, false, mCurPage); //    企业  申请  个人 有审批
                        } else {
                            ComApplyOrInvitePersonActivity.start(requireActivity(), qualityMemberBean, false, mCurPage);  //    企业  申请  个人
                        }
                    }
                }
                break;
        }
    }

    private void initPopup() {
        mBinding.popBusinessType.setVisibility(View.VISIBLE);
        mBinding.popAddress.setVisibility(View.VISIBLE);
        mBinding.popMemberType.setVisibility(View.VISIBLE);
        mBinding.popBusinessType.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popAddress.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popMemberType.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        initCateGoryPopup();
    }

    public void showCategoryPop() {
        mBinding.popLine.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(mNo6)) {
            mBinding.popBusinessType.updateChooseTextStatus(-2, null);
        } else {
            mBinding.popBusinessType.updateChooseTextStatus(-1, mBinding.popBusinessType.getKeyName());
        }
        popCategory.showPopwindow0(mBinding.popLine);
    }

    @Override
    public void onLoadChooseData(String mKeyName) {
        switch (mKeyName) {
            case "主营业务":
                showCategoryPop();
                break;
            case "区域":
                sModel.getAddressModel(PickCateType.TYPE_1);
                break;
            case "会员主体":
                sModel.getMemberTypes(PickCateType.TYPE_2);
                break;
        }
    }

    private String mNo6;
    private String mNo7;

    /**
     * 主营业务弹窗
     */
    private MThreeLevelFilterWindow popCategory;

    private void initCateGoryPopup() {
        popCategory = new MThreeLevelFilterWindow(getActivity());
        popCategory.setBgView(mBinding.grayLayout);
        popCategory.setThreeLeveGone(false);
        popCategory.setOnResultClick(new MThreeLevelFilterWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                CommonPopEntity pickResultProject1 = (CommonPopEntity) key1;
                CommonPopEntity pickResultProject2 = (CommonPopEntity) key2;
                mNo6 = pickResultProject1.getNo();
                mNo7 = pickResultProject2.getNo();
                mBinding.popBusinessType.updateChooseTextStatus(0, mBinding.popBusinessType.getKeyName());
                mBusinessNo = "";
                if (!TextUtils.isEmpty(mNo6)) {
                    mBusinessNo = mNo6;
                    mBinding.popBusinessType.updateChooseTextStatus(1, pickResultProject1.getTypeName());
                    if (!TextUtils.isEmpty(mNo7)) {
                        mBusinessNo = mNo7;
                        mBinding.popBusinessType.updateChooseTextStatus(1, pickResultProject2.getTypeName());
                    }
                }
                loadData(false);
            }

            @Override
            public void reset() {
                mNo6 = "";
                mNo7 = "";
                mBusinessNo = "";
                mBinding.popBusinessType.updateChooseTextStatus(0, mBinding.popBusinessType.getKeyName());
                loadData(false);
            }
        });
        popCategory.setOnDismissListener(() -> {
            if (!TextUtils.isEmpty(mNo6) || !TextUtils.isEmpty(mNo7)) {
                mBinding.popBusinessType.updateChooseTextStatus(1, null);
            } else {
                mBinding.popBusinessType.updateChooseTextStatus(0, mBinding.popBusinessType.getKeyName());
            }
        });
    }


    public void setChooseItemData(int type, List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        switch (type) {
            case PickCateType.TYPE_0:
                popCategory.setData(data, 0);
                break;
            case PickCateType.TYPE_1:
                mBinding.popAddress.setData(data);
                mBinding.popAddress.showPop();
                break;
            case PickCateType.TYPE_2:
                mBinding.popMemberType.setData(data);
                mBinding.popMemberType.showPop();
                break;
        }
    }


    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        String no = position == 0 ? "" : entity.getNo();
        String id = position == 0 ? "" : entity.getId();
        switch (mKeyName) {
//            case "主营业务":
//                if (!TextUtils.equals(id, mBusinessNo)) {
//                    mBusinessNo = id;
//                    loadData(false);
//                }
//                break;
            case "区域":
                if (!TextUtils.equals(no, mAreaNo)) {
                    mAreaNo = no;
                    loadData(false);
                }
                break;
            case "会员主体":
                userType = no;
                loadData(false);
                break;
        }
    }

    /**
     * -------------------------------------initRecycler------------------------------------------
     */
    private void initRecycler() {
        TextView textView = mBinding.empView.findViewById(R.id.no_data_count);
        textView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setPullRefreshEnabled(true);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        LoadingMoreFooter footer = (LoadingMoreFooter) mBinding.recyclerView.getFootView();
        footer.setNoMoreHint("已经到底啦~");
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(false);
            }

            @Override
            public void onLoadMore() {
                loadData(true);
            }
        });
        initRecyclerAdapter();
    }

    private void initRecyclerAdapter() {
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new MemberInviteAdapter(getContext(), new ArrayList<>(), true) {
            @Override
            public void onCheckedUpdate(List<QualityMemberBean> array) {
                if (array.size() > 0) {
                    qualityMemberBean = array.get(0);
                    qualityMemberBean.setCompanyNo(qualityMemberBean.getNo()); // 邀请加盟列表页面no==companyNo
                    mBinding.tvChooseMember.setText(Html.fromHtml(String.format(getResources().getString(R.string.select_apply_member), qualityMemberBean.getCompanyName())));
                } else {
                    qualityMemberBean = null;
                    mBinding.tvChooseMember.setText(Html.fromHtml(String.format(getResources().getString(R.string.select_apply_member), "")));
                }
            }
        };
        mAdapter.setOnItemClick(new AdapterOnItemClick<QualityMemberBean>() {
            @Override
            public void onItemClick(QualityMemberBean memberBean, int position) {
                if (!TextUtils.isEmpty(memberBean.getNo())) { // no为企业No
                    if (memberBean.getUserType().equals("1")) {
                        MemberConfig.getInstance().startWebsiteInfo(getContext(), memberBean.getNo(), 1);
                    } else {
                        MemberConfig.getInstance().startWebsiteInfo(getContext(), memberBean.getNo(), 0);//个人
                    }
                } else {
                    MToast.showToast(getContext(), "店铺No为空");
                }
            }
        });
        mBinding.recyclerView.setAdapter(mAdapter);
    }

    public void closeRecyclerRefreshing() {
        mBinding.recyclerView.refreshComplete();
        mBinding.recyclerView.loadMoreComplete();
    }

    public void showEmpty() {
        mAdapter.clearDatas();
        mBinding.empView.setVisibility(View.VISIBLE);
    }

    public void refreshRecycler(List<QualityMemberBean> list, boolean isLoadMore, boolean noMoreData) {
        closeRecyclerRefreshing();
        mBinding.recyclerView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setLoadingMoreEnabled(!noMoreData);
        if (isLoadMore) {
            if (list != null && list.size() > 0) {
                mAdapter.addDatas(list);
            }
        } else {
            if (list != null && list.size() > 0) {
                mBinding.empView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
            } else {
                mAdapter.clearDatas();
                mBinding.empView.setVisibility(View.VISIBLE);
            }
        }
    }


}
